package com.homepage.web.rest;

import com.homepage.repository.FeaturetteRepository;
import com.homepage.service.FeaturetteService;
import com.homepage.service.dto.FeaturetteDTO;
import com.homepage.util.HeaderUtil;
import com.homepage.util.ResponseUtil;
import com.homepage.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.StreamSupport;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


/**
 * REST controller for managing {@link com.homepage.domain.Featurette}.
 */
@RestController
@RequestMapping("/company")
public class FeaturetteResource {

    private final Logger log = LoggerFactory.getLogger(FeaturetteResource.class);

    private static final String ENTITY_NAME = "featurette";

    @Value("${common.clientApp.name}")
    private String applicationName;

    private final FeaturetteService featuretteService;

    private final FeaturetteRepository featuretteRepository;

    public FeaturetteResource(FeaturetteService featuretteService, FeaturetteRepository featuretteRepository) {
        this.featuretteService = featuretteService;
        this.featuretteRepository = featuretteRepository;
    }

    /**
     * {@code POST  /featurettes} : Create a new featurette.
     *
     * @param featuretteDTOS the featuretteDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new featuretteDTO, or with status {@code 400 (Bad Request)} if the featurette has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/{companyName}/featurettes")
    public ResponseEntity<List<FeaturetteDTO>> createFeaturette(@Valid @RequestBody List<FeaturetteDTO> featuretteDTOS,
                                                          @PathVariable String companyName) throws URISyntaxException {
        for(FeaturetteDTO featuretteDTO : featuretteDTOS)
        {
            featuretteDTO.setCompanyId(companyName);
        }

        log.debug("REST request to save Featurette : {}", featuretteDTOS);

        List<FeaturetteDTO> result = featuretteService.saveAll(featuretteDTOS);
        return ResponseEntity
            .created(new URI("/company/"+ companyName +"/featurettes/"))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, "BATCH WAY"))
            .body(result);
    }

    @GetMapping("/{companyName}/featurettes")
    public List<FeaturetteDTO> createFeaturette(@PathVariable String companyName) {
        return featuretteService.getAllByCompanyId(companyName);
    }

    /**
     * {@code PUT  /featurettes/:id} : Updates an existing featurette.
     *
     * @param id the id of the featuretteDTO to save.
     * @param featuretteDTO the featuretteDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated featuretteDTO,
     * or with status {@code 400 (Bad Request)} if the featuretteDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the featuretteDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/featurettes/{id}")
    public ResponseEntity<FeaturetteDTO> updateFeaturette(
        @PathVariable(value = "id", required = false) final Long id,
        @Valid @RequestBody FeaturetteDTO featuretteDTO
    ) throws URISyntaxException {
        log.debug("REST request to update Featurette : {}, {}", id, featuretteDTO);
        if (featuretteDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, featuretteDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!featuretteRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        FeaturetteDTO result = featuretteService.save(featuretteDTO);
        return ResponseEntity
            .ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, featuretteDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code PATCH  /featurettes/:id} : Partial updates given fields of an existing featurette, field will ignore if it is null
     *
     * @param id the id of the featuretteDTO to save.
     * @param featuretteDTO the featuretteDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated featuretteDTO,
     * or with status {@code 400 (Bad Request)} if the featuretteDTO is not valid,
     * or with status {@code 404 (Not Found)} if the featuretteDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the featuretteDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/featurettes/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<FeaturetteDTO> partialUpdateFeaturette(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody FeaturetteDTO featuretteDTO
    ) throws URISyntaxException {
        log.debug("REST request to partial update Featurette partially : {}, {}", id, featuretteDTO);
        if (featuretteDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, featuretteDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!featuretteRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<FeaturetteDTO> result = featuretteService.partialUpdate(featuretteDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, featuretteDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /featurettes} : get all the featurettes.
     *
     * @param filter the filter of the request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of featurettes in body.
     */
    @GetMapping("/featurettes")
    public List<FeaturetteDTO> getAllFeaturettes(@RequestParam(required = false) String filter) {
        if ("featuretteimage-is-null".equals(filter)) {
            log.debug("REST request to get all Featurettes where featuretteImage is null");
            return featuretteService.findAllWhereFeaturetteImageIsNull();
        }
        log.debug("REST request to get all Featurettes");
        return featuretteService.findAll();
    }

    /**
     * {@code GET  /featurettes/:id} : get the "id" featurette.
     *
     * @param id the id of the featuretteDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the featuretteDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/featurettes/{id}")
    public ResponseEntity<FeaturetteDTO> getFeaturette(@PathVariable Long id) {
        log.debug("REST request to get Featurette : {}", id);
        Optional<FeaturetteDTO> featuretteDTO = featuretteService.findOne(id);
        return ResponseUtil.wrapOrNotFound(featuretteDTO);
    }

    /**
     * {@code DELETE  /featurettes/:id} : delete the "id" featurette.
     *
     * @param id the id of the featuretteDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/featurettes/{id}")
    public ResponseEntity<Void> deleteFeaturette(@PathVariable Long id) {
        log.debug("REST request to delete Featurette : {}", id);
        featuretteService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
